<?php

namespace App\Api\Dao;

use App\Exceptions\DaoException;
use App\Helpers\ResponseEnum;
use App\Models\TongUser;
use App\Models\TongUserBank;
use App\Models\TongUserWithdrawal;
use Illuminate\Support\Facades\DB;

class WithdrawalDao extends BaseDao
{

    /**
     * 查询构造器
     * @param $data
     * @return \Illuminate\Database\Eloquent\Builder
     */
    function getBuildQuery($data)
    {
        $query = TongUserWithdrawal::query();
        // TODO: Implement getBuildQuery() method.
        if(checkIsHasField($data,'id')){
            $query->where('id',$data['id']);
        }
        if(checkIsHasField($data,'u_id')){
            $query->where('u_id',$data['u_id']);
        }
        return $query;
    }

    /**
     * 用户申请提现
     * @return \Illuminate\Database\Eloquent\Builder|\Illuminate\Database\Eloquent\Model|void
     */
    public function applyWithdrawal($data)
    {
        DB::beginTransaction();
        try {
            //酱用户的金额给扣除掉
            TongUser::query()->where('id',$data['u_id'])->decrement('money',$data['money']);
            $data['real_money'] = bcsub($data['money'],bcmul($data['money'],bcdiv(config("withdrawal.shouxufei"),100,2),2),2);
            $data['bank_json_data'] = TongUserBank::query()->where('id',$data['bank_id'])->first();
            $result = TongUserWithdrawal::query()->create($data);
            DB::commit();
            return $result;
        }catch (\Exception $exception){
            DB::rollBack();
            throw new DaoException(ResponseEnum::HTTP_ERROR,'申请失败');
        }


    }

    /**
     * 获取提现的记录
     * @param array $data
     * @return \Illuminate\Contracts\Pagination\LengthAwarePaginator
     */
    public function getWithdrawalList(array $data)
    {
        return $this->getBuildQuery($data)->orderBy('id','desc')->paginate($data['pageSize']);
    }

}
